<template>
  <div class="app-container">
    <!-- 动态数据库连接配置区域 -->
    <el-card class="box-card" shadow="never" style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <span>
            <el-icon class="el-icon-setting" />
            动态数据库连接配置
          </span>
          <div>
            <el-tag v-if="connected" type="success" size="small">
              <el-icon class="el-icon-success" />
              已连接: {{ currentDbInfo }}
            </el-tag>
            <el-tag v-else type="info" size="small">
              <el-icon class="el-icon-info" />
              未连接
            </el-tag>
            <el-switch
              v-model="showDbConfig"
              active-text="显示配置"
              inactive-text="隐藏配置"
              style="margin-left: 20px;"
            />
          </div>
        </div>
      </template>

      <div v-show="showDbConfig">
        <el-form :model="dbConfig" ref="dbConfigRef" :rules="dbConfigRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="数据库类型" prop="dbType">
                <el-select v-model="dbConfig.dbType" placeholder="请选择数据库类型" style="width: 100%;">
                  <el-option
                    v-for="(label, value) in dbTypes"
                    :key="value"
                    :label="label"
                    :value="value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="主机地址" prop="host">
                <el-input v-model="dbConfig.host" placeholder="请输入主机地址" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="端口号" prop="port">
                <el-input-number
                  v-model="dbConfig.port"
                  :min="1"
                  :max="65535"
                  placeholder="端口号"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数据库名" prop="database">
                <el-input v-model="dbConfig.database" placeholder="请输入数据库名" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="dbConfig.username" placeholder="请输入用户名" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="dbConfig.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="dbConfig.dbType === 'postgresql' || dbConfig.dbType === 'oracle'">
              <el-form-item label="模式名" prop="schema">
                <el-input v-model="dbConfig.schema" placeholder="请输入模式名(可选)" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-checkbox v-model="saveConnection">保存连接信息</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item>
                <el-button type="primary" @click="testConnection" :loading="testing" icon="Connection">
                  测试连接
                </el-button>
                <el-button type="success" @click="handleSyncTableStructure" :loading="syncing" :disabled="!connected" icon="Refresh">
                  同步表结构
                </el-button>
                <el-button type="info" @click="showSavedConnections" v-if="savedConnections.length > 0" icon="Folder">
                  已保存连接 ({{ savedConnections.length }})
                </el-button>
                <el-button type="warning" @click="disconnectDb" v-if="connected" icon="Close">
                  断开连接
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 连接状态指示 -->
        <el-alert
          v-if="connectionStatus.show"
          :title="connectionStatus.title"
          :type="connectionStatus.type"
          :description="connectionStatus.description"
          show-icon
          :closable="false"
          style="margin-top: 10px;"
        />

        <!-- 已保存连接列表 -->
        <el-collapse v-if="showSavedConnectionsList && savedConnections.length > 0" style="margin-top: 15px;">
          <el-collapse-item title="已保存的连接" name="savedConnections">
            <div style="max-height: 200px; overflow-y: auto;">
              <div
                v-for="(conn, index) in savedConnections"
                :key="index"
                class="saved-connection-item"
                @click="loadSavedConnection(conn)"
              >
                <div class="connection-info">
                  <div class="connection-name">{{ conn.name }}</div>
                  <div class="connection-details">
                    {{ conn.dbType }} - {{ conn.host }}:{{ conn.port }}/{{ conn.database }}
                  </div>
                </div>
                <el-button
                  type="text"
                  size="small"
                  @click.stop="deleteSavedConnection(index)"
                  style="color: #f56c6c;"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>

    <!-- 表结构同步预览区域 -->
    <el-card v-if="showSyncPreview" class="box-card" shadow="never" style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <span>
            <el-icon class="el-icon-view" />
            表结构同步预览
          </span>
          <el-button type="text" @click="closeSyncPreview" icon="Close">
            关闭预览
          </el-button>
        </div>
      </template>

      <div>
        <el-alert
          title="即将同步的表结构信息"
          type="info"
          description="请确认以下表结构信息无误后，点击确认同步按钮"
          show-icon
          :closable="false"
          style="margin-bottom: 15px;"
        />

        <el-table :data="syncPreviewData" border style="width: 100%" max-height="400">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="tableName" label="表名称" width="200" />
          <el-table-column prop="tableComment" label="表描述" width="200" />
          <el-table-column prop="columnCount" label="字段数量" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="text" @click="previewTableStructure(scope.row)">
                预览字段
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 15px; text-align: right;">
          <el-button @click="closeSyncPreview">取消</el-button>
          <el-button type="primary" @click="confirmSync" :loading="confirmingSyncLoading">
            确认同步选中表
          </el-button>
        </div>
      </div>
    </el-card>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="queryParams.tableComment"
          placeholder="请输入表描述"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          :disabled="multiple"
          @click="handleGenTable"
          v-hasPermi="['tool:gen:code']"
        >生成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          disabled
          @click="showDevelopmentTip"
          v-hasRole="['admin']"
        >创建</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          disabled
          @click="showDevelopmentTip"
          v-hasPermi="['tool:gen:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Connection"
          @click="openExternalDbDialog"
          v-hasPermi="['tool:gen:import']"
        >连接外部数据库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleEditTable"
          v-hasPermi="['tool:gen:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tool:gen:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="genRef" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="表名称" align="center" prop="tableName" :show-overflow-tooltip="true" />
      <el-table-column label="表描述" align="center" prop="tableComment" :show-overflow-tooltip="true" />
      <el-table-column label="实体" align="center" prop="className" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable="custom" :sort-orders="['descending', 'ascending']" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" sortable="custom" :sort-orders="['descending', 'ascending']" />
      <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="预览" placement="top">
            <el-button link type="primary" icon="View" @click="handlePreview(scope.row)" v-hasPermi="['tool:gen:preview']"></el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleEditTable(scope.row)" v-hasPermi="['tool:gen:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tool:gen:remove']"></el-button>
          </el-tooltip>
          <el-tooltip content="同步" placement="top">
            <el-button link type="primary" icon="Refresh" @click="handleSynchDb(scope.row)" v-hasPermi="['tool:gen:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="生成代码" placement="top">
            <el-button link type="primary" icon="Download" @click="handleGenTable(scope.row)" v-hasPermi="['tool:gen:code']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览界面 -->
    <el-dialog :title="preview.title" v-model="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :key="value"
        >
          <el-link :underline="false" icon="DocumentCopy" v-copyText="value" v-copyText:callback="copyTextSuccess" style="float:right">&nbsp;复制</el-link>
          <pre>{{ value }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <import-table ref="importRef" @ok="handleQuery" />
    <create-table ref="createRef" @ok="handleQuery" />
    <external-db-dialog ref="externalDbRef" @ok="handleQuery" />
  </div>
</template>

<script setup name="Gen">
import { ref, reactive, onActivated, onMounted, watch, computed, toRefs, getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// 移除图标导入，使用字符串形式的图标
import {
  listTable, previewTable, delTable, genCode, synchDb,
  testExternalDbConnection, listExternalDbTables, importExternalTables,
  getSupportedDbTypes, cleanupExternalConnections, syncTableStructure
} from "@/api/tool/gen"
import router from "@/router"
import importTable from "./importTable"
import createTable from "./createTable"
import externalDbDialog from "./externalDbDialog"

const route = useRoute()
const { proxy } = getCurrentInstance()

// 基础数据
const tableList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const tableNames = ref([])
const dateRange = ref([])
const uniqueId = ref("")
const defaultSort = ref({ prop: "createTime", order: "descending" })

// 动态数据库连接相关数据
const showDbConfig = ref(false)
const connected = ref(false)
const testing = ref(false)
const syncing = ref(false)
const saveConnection = ref(false)
const savedConnections = ref([])
const showSavedConnectionsList = ref(false)
const dbTypes = ref({})

// 表结构同步预览相关数据
const showSyncPreview = ref(false)
const syncPreviewData = ref([])
const confirmingSyncLoading = ref(false)

// 数据库配置
const dbConfig = reactive({
  dbType: 'mysql',
  host: 'localhost',
  port: 3306,
  database: '',
  username: '',
  password: '',
  schema: ''
})

// 连接状态
const connectionStatus = reactive({
  show: false,
  title: '',
  type: 'info',
  description: ''
})

// 表单验证规则
const dbConfigRules = {
  dbType: [{ required: true, message: '数据库类型不能为空', trigger: 'change' }],
  host: [{ required: true, message: '主机地址不能为空', trigger: 'blur' }],
  port: [{ required: true, message: '端口号不能为空', trigger: 'blur' }],
  database: [{ required: true, message: '数据库名不能为空', trigger: 'blur' }],
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
}

// 表单引用
const dbConfigRef = ref()

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tableName: undefined,
    tableComment: undefined,
    orderByColumn: defaultSort.value.prop,
    isAsc: defaultSort.value.order
  },
  preview: {
    open: false,
    title: "代码预览",
    data: {},
    activeName: "domain.java"
  }
})

const { queryParams, preview } = toRefs(data)

// 计算属性
const currentDbInfo = computed(() => {
  if (connected.value) {
    return `${dbConfig.dbType}://${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`
  }
  return ''
})

// 组件挂载时初始化
onMounted(() => {
  loadDbTypes()
  loadSavedConnectionsFromLocal()
})

// 监听数据库类型变化，设置默认端口
watch(() => dbConfig.dbType, (newType) => {
  switch (newType) {
    case 'mysql':
      dbConfig.port = 3306
      break
    case 'postgresql':
      dbConfig.port = 5432
      break
    case 'oracle':
      dbConfig.port = 1521
      break
    case 'sqlserver':
      dbConfig.port = 1433
      break
  }
})

onActivated(() => {
  const time = route.query.t
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time
    queryParams.value.pageNum = Number(route.query.pageNum)
    dateRange.value = []
    proxy.resetForm("queryForm")
    getList()
  }
})

/** 查询表集合 */
function getList() {
  loading.value = true
  listTable(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    tableList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 生成代码操作 */
function handleGenTable(row) {
  const tbNames = row.tableName || tableNames.value
  if (tbNames == "") {
    proxy.$modal.msgError("请选择要生成的数据")
    return
  }
  if (row.genType === "1") {
    genCode(row.tableName).then(response => {
      proxy.$modal.msgSuccess("成功生成到自定义路径：" + row.genPath)
    })
  } else {
    proxy.$download.zip("/tool/gen/batchGenCode?tables=" + tbNames, "ruoyi.zip")
  }
}

/** 同步数据库操作 */
function handleSynchDb(row) {
  const tableName = row.tableName
  proxy.$modal.confirm('确认要强制同步"' + tableName + '"表结构吗？').then(function () {
    return synchDb(tableName)
  }).then(() => {
    proxy.$modal.msgSuccess("同步成功")
  }).catch(() => {})
}

/** 打开导入表弹窗 */
function openImportTable() {
  proxy.$refs["importRef"].show()
}

/** 打开创建表弹窗 */
function openCreateTable() {
  proxy.$refs["createRef"].show()
}

/** 打开外部数据库连接弹窗 */
function openExternalDbDialog() {
  proxy.$refs["externalDbRef"].show()
}

/** 显示功能开发中提示 */
function showDevelopmentTip() {
  proxy.$modal.msgWarning("该功能正在二次开发中，敬请期待！")
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  queryParams.value.pageNum = 1
  proxy.$refs["genRef"].sort(defaultSort.value.prop, defaultSort.value.order)
}

/** 预览按钮 */
function handlePreview(row) {
  previewTable(row.tableId).then(response => {
    preview.value.data = response.data
    preview.value.open = true
    preview.value.activeName = "domain.java"
  })
}

/** 复制代码成功 */
function copyTextSuccess() {
  proxy.$modal.msgSuccess("复制成功")
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.tableId)
  tableNames.value = selection.map(item => item.tableName)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 排序触发事件 */
function handleSortChange(column, prop, order) {
  queryParams.value.orderByColumn = column.prop
  queryParams.value.isAsc = column.order
  getList()
}

/** 修改按钮操作 */
function handleEditTable(row) {
  const tableId = row.tableId || ids.value[0]
  const tableName = row.tableName || tableNames.value[0]
  const params = { pageNum: queryParams.value.pageNum }
  proxy.$tab.openPage("修改[" + tableName + "]生成配置", '/tool/gen-edit/index/' + tableId, params)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const tableIds = row.tableId || ids.value
  proxy.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？').then(function () {
    return delTable(tableIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 获取支持的数据库类型 */
function loadDbTypes() {
  getSupportedDbTypes().then(res => {
    if (res.code === 200) {
      dbTypes.value = res.data
    }
  }).catch(() => {
    // 如果获取失败，使用默认值
    dbTypes.value = {
      'mysql': 'MySQL',
      'postgresql': 'PostgreSQL',
      'oracle': 'Oracle',
      'sqlserver': 'SQL Server'
    }
  })
}

/** 测试数据库连接 */
function testConnection() {
  if (!dbConfigRef.value) return

  dbConfigRef.value.validate(valid => {
    if (valid) {
      testing.value = true
      testExternalDbConnection(dbConfig).then(res => {
        if (res.code === 200) {
          connected.value = true
          connectionStatus.show = true
          connectionStatus.title = '连接成功'
          connectionStatus.type = 'success'
          connectionStatus.description = `已成功连接到 ${currentDbInfo.value}`

          ElMessage.success('数据库连接成功')

          // 如果勾选了保存连接，则保存到本地缓存
          if (saveConnection.value) {
            saveConnectionToLocal()
          }
        } else {
          connected.value = false
          connectionStatus.show = true
          connectionStatus.title = '连接失败'
          connectionStatus.type = 'error'
          connectionStatus.description = res.msg || '连接失败，请检查配置信息'

          ElMessage.error(res.msg || '连接失败')
        }
      }).catch(error => {
        connected.value = false
        connectionStatus.show = true
        connectionStatus.title = '连接异常'
        connectionStatus.type = 'error'
        connectionStatus.description = '连接失败: ' + error.message

        ElMessage.error('连接失败: ' + error.message)
      }).finally(() => {
        testing.value = false
      })
    }
  })
}

/** 同步表结构预览 */
function handleSyncTableStructure() {
  if (!connected.value) {
    ElMessage.warning('请先连接数据库')
    return
  }

  syncing.value = true

  // 获取外部数据库表列表进行预览
  const queryParams = {
    pageNum: 1,
    pageSize: 1000, // 获取全量数据
    tableName: '',
    tableComment: ''
  }

  listExternalDbTables(dbConfig, queryParams).then(res => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      syncPreviewData.value = res.rows.map(table => ({
        ...table,
        columnCount: table.columns ? table.columns.length : 0
      }))
      showSyncPreview.value = true
      ElMessage.success(`发现 ${res.rows.length} 个表，请选择要同步的表`)
    } else {
      ElMessage.warning('未发现可同步的表')
    }
  }).catch(error => {
    ElMessage.error('获取表列表失败: ' + error.message)
  }).finally(() => {
    syncing.value = false
  })
}

/** 断开数据库连接 */
function disconnectDb() {
  connected.value = false
  connectionStatus.show = false
  showSyncPreview.value = false
  syncPreviewData.value = []
  ElMessage.success('已断开数据库连接')
}

/** 显示已保存连接 */
function showSavedConnections() {
  showSavedConnectionsList.value = !showSavedConnectionsList.value
}

/** 关闭同步预览 */
function closeSyncPreview() {
  showSyncPreview.value = false
  syncPreviewData.value = []
}

/** 预览表结构 */
function previewTableStructure(table) {
  ElMessageBox.alert(
    `表名: ${table.tableName}\n表描述: ${table.tableComment}\n字段数量: ${table.columnCount}`,
    '表结构信息',
    {
      confirmButtonText: '确定'
    }
  )
}

/** 确认同步 */
function confirmSync() {
  // 这里需要获取选中的表
  const selectedTables = syncPreviewData.value.filter(table => table.selected)

  if (selectedTables.length === 0) {
    ElMessage.warning('请选择要同步的表')
    return
  }

  ElMessageBox.confirm(
    `确认同步选中的 ${selectedTables.length} 个表吗？`,
    '确认同步',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    confirmingSyncLoading.value = true

    const syncData = {
      dbConfig: dbConfig,
      tableNames: selectedTables.map(table => table.tableName)
    }

    syncTableStructure(syncData).then(res => {
      if (res.code === 200) {
        ElMessage.success(res.msg)
        showSyncPreview.value = false
        syncPreviewData.value = []
        getList() // 刷新表列表
      } else {
        ElMessage.error(res.msg || '同步失败')
      }
    }).catch(error => {
      ElMessage.error('同步失败: ' + error.message)
    }).finally(() => {
      confirmingSyncLoading.value = false
    })
  })
}

/** 保存连接信息到本地缓存 */
function saveConnectionToLocal() {
  try {
    const connectionName = `${dbConfig.dbType}-${dbConfig.host}-${dbConfig.database}`
    const connectionInfo = {
      name: connectionName,
      dbType: dbConfig.dbType,
      host: dbConfig.host,
      port: dbConfig.port,
      database: dbConfig.database,
      username: dbConfig.username,
      password: dbConfig.password,
      schema: dbConfig.schema,
      savedAt: new Date().toISOString()
    }

    // 检查是否已存在相同的连接
    const existingIndex = savedConnections.value.findIndex(conn =>
      conn.dbType === connectionInfo.dbType &&
      conn.host === connectionInfo.host &&
      conn.port === connectionInfo.port &&
      conn.database === connectionInfo.database &&
      conn.username === connectionInfo.username
    )

    if (existingIndex >= 0) {
      // 更新现有连接
      savedConnections.value[existingIndex] = connectionInfo
      ElMessage.success('连接信息已更新')
    } else {
      // 添加新连接
      savedConnections.value.push(connectionInfo)
      ElMessage.success('连接信息已保存')
    }

    // 保存到localStorage
    localStorage.setItem('external_db_connections', JSON.stringify(savedConnections.value))
  } catch (error) {
    ElMessage.error('保存连接信息失败: ' + error.message)
  }
}

/** 从本地缓存加载已保存的连接 */
function loadSavedConnectionsFromLocal() {
  try {
    const saved = localStorage.getItem('external_db_connections')
    if (saved) {
      savedConnections.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载已保存的连接失败:', error)
    savedConnections.value = []
  }
}

/** 加载选中的连接信息 */
function loadSavedConnection(connection) {
  Object.assign(dbConfig, {
    dbType: connection.dbType,
    host: connection.host,
    port: connection.port,
    database: connection.database,
    username: connection.username,
    password: connection.password,
    schema: connection.schema || ''
  })

  showSavedConnectionsList.value = false
  ElMessage.success('连接信息已加载')
}

/** 删除已保存的连接 */
function deleteSavedConnection(index) {
  ElMessageBox.confirm(
    '确认删除这个已保存的连接吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    savedConnections.value.splice(index, 1)
    localStorage.setItem('external_db_connections', JSON.stringify(savedConnections.value))
    ElMessage.success('连接已删除')
  }).catch(() => {
    // 用户取消删除
  })
}

getList()
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  margin-bottom: 20px;
}

.saved-connection-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.saved-connection-item:hover {
  background-color: #f5f7fa;
}

.connection-info {
  flex: 1;
}

.connection-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.connection-details {
  font-size: 12px;
  color: #666;
}

.el-alert {
  margin-bottom: 15px;
}

.el-table {
  margin-bottom: 15px;
}
</style>
